let app = getApp()
const util = require('../../utils/util.js')
import { request } from "../../utils/request.js";


Page({

    /**
     * 页面的初始数据
     */
    data: {
        // chooseGroup,
        showGroupIndex: 0,
        // groups: [
        //     { text: '默认账单', value: 0 },
        //     { text: '测试账单', value: 1 },
        // ],
        inputvalue: '',
        kind_list_out: [],
        kind_list_in: [],
        set_money: '',
        write_kind_list: [{
            word: '支出',
            choose: true,
            type: 0
        },
        {
            word: '入账',
            choose: false,
            type: 1
        }
        ],
        add_date_show: '今天',
        selected: [],
        show: false,
        currentDate: new Date().getTime(),
        // currentDate: "",
        configColor: app.globalData.configColor,
        isFocus: true,
        isFocusForRemark: false,
        showChooseTitle: false,
        columns: [''],
        // selectedColumnIndex: 0,
        // selectedColumnValue:  '记一笔',
        remarkList: [],
        statusBarHeight: app.globalData.statusBarHeight,
        navBarHeight: app.globalData.navBarHeight,
        timeoutID: null,
        delayTime: 0
    },
    changeGroup(valueTemp) {
        this.setData({
            showGroupIndex: valueTemp.detail
        })
        this.data.groups.forEach((item) => {
            if (item.value == valueTemp.detail) {
                this.setData({
                    chooseGroup: item
                })
            }
        })
        // 切换账本
        wx.request({
            url: app.globalData.url + '/updateUserGroupChoose',
            method: 'GET',
            data: {
                groupId: this.data.chooseGroup.groupId,
                userId: wx.getStorageSync('userInfo').id,
            },
            success: (res) => {
                let re = res.data
                if (re.flag) {
                    let userInfo = wx.getStorageSync('userInfo');
                    userInfo.groupVO = re.data
                    wx.setStorageSync('userInfo', userInfo);
                    app.globalData.cache_year_index = 0;
                    app.globalData.cache_month_index = 0;
                } else {
                    wx.showToast({
                        title: '选择失败，请重试',
                        icon: 'none'
                    })
                }
            }
        })
        // 切换类别
        let that = this
        request({
            url: "/getCategoryByGroupId",
            method: "GET",
            data: {
                groupId: this.data.chooseGroup.groupId,
                userId: wx.getStorageSync('userInfo').id
            }
        }).then((responseData) => {
            that.getRemarkByCategory(responseData.outCategory[0].categoryId)
            this.setData({
                currentDate: new Date().getTime(),
                kind_list_out: responseData.outCategory,
                kind_list_in: responseData.inCategory,
            })
        })
    },
    go_index() {
        wx.switchTab({
            url: '/pages/index/index',
        });
    },
    // 选择支出或者入账
    choose_type(e) {
        let write_kind_list = this.data.write_kind_list
        write_kind_list.forEach((item) => {
            item.choose = false
        })
        let index = e.currentTarget.dataset.index * 1
        write_kind_list[index].choose = true
        this.setData({
            write_kind_list: write_kind_list,
            isFocus: true
        })
        // 更改备注提示
        let categoryId = 0;
        if (index == 0) {
            this.data.kind_list_out.forEach((item) => {
                if (item.choose) {
                    categoryId = item.categoryId
                    return;
                }
            })
        } else {
            this.data.kind_list_in.forEach((item) => {
                if (item.choose) {
                    categoryId = item.categoryId
                    return;
                }
            })
        }
        this.getRemarkByCategory(categoryId);
    },
    // 选择类型
    choose_kinds(e) {
        let kind_list = this.data.kind_list_in
        let isOut = this.data.write_kind_list[0].choose
        if (isOut) {
            kind_list = this.data.kind_list_out
        }
        kind_list.forEach((item) => {
            item.choose = false
        })
        let index = e.currentTarget.dataset.index * 1
        kind_list[index].choose = true
        // 更新备注
        this.getRemarkByCategory(kind_list[index].categoryId)
        if (isOut) {
            this.setData({
                kind_list_out: kind_list,
                isFocus: true
            })
        } else {
            this.setData({
                kind_list_in: kind_list,
                isFocus: true
            })
        }
    },
    showPopup(e) {
        this.setData({
            show: true
        });
    },
    onClose() {
        this.setData({
            show: false,
            showChooseTitle: false
        });
        let that = this
        setTimeout(function () {
            that.setData({
                columns: [''],
            });
        }, 200);

    },
    onConfirm(event) {
        this.setData({ show: false });
        this.setData({
            currentDate: event.detail
        });

        let chooseYear = new Date(this.data.currentDate).getFullYear()
        let chooseMonth = new Date(this.data.currentDate).getMonth() + 1
        let chooseDay = new Date(this.data.currentDate).getDate()
        let nowYear = new Date().getFullYear()
        let nowMonth = new Date().getMonth() + 1
        let nowDay = new Date().getDate()

        if (chooseYear == nowYear && chooseMonth == nowMonth && chooseDay == nowDay) {
            this.setData({
                add_date_show: '今天',
            });
        } else {
            this.setData({
                add_date_show: chooseMonth + '-' + chooseDay
            });
        }
    },
    onCancel() {
        this.setData({
            show: false
        });
    },
    openChooseTitle() {
        wx.request({
            url: app.globalData.url + '/getAllCarName',
            method: 'GET',
            data: {
                userId: wx.getStorageSync('userInfo').id,
            },
            success: (res) => {
                if (res.data.flag) {
                    let columnsTemp = this.data.columns
                    res.data.data.forEach((item) => {
                        columnsTemp.push(item)
                    })
                    this.setData({
                        columns: columnsTemp,
                        showChooseTitle: true
                    })
                } else {
                    wx.showToast({
                        title: '车牌查询失败，请稍后尝试',
                        icon: 'none'
                    })
                }
            },
            fail: (err) => {
                console.log('车牌查询失败，请稍后尝试!!!', err);
            }
        })
    },
    // 选择日常还是记油耗
    onChangeTitle(event) {
        const { picker, value, index } = event.detail;
        // console.log(index+","+value)
        // this.setData({ 
        //     selectedColumnIndex: index ,
        //     selectedColumnValue: value 
        // })
        // 记油耗
        if (index != 0) {
            wx.redirectTo({
                url: '/pages/add_oil/add_oil?selectedColumnValue=' + value
            })
        }

    },
    // 提交表单
    submit(e) {
        let money = e.detail.value.money
        let remark = e.detail.value.remark
        let isGoon = e.detail.target.dataset.goon
        if (!this.data.chooseGroup || this.data.showGroupIndex == 0) {
            wx.showToast({
                title: '请选择账本',
                icon: 'none'
            })
            return
        }
        if (!money) {
            wx.showToast({
                title: '请输入具体金额',
                icon: 'none'
            })
            return
        }
        const regex = /^\d+(\.\d{1,2})?$/;
        if (!regex.test(money)) {
            const regexTemp = /^\d+\.\d{3,}$/;
            if (regexTemp.test(money)) {
                wx.showToast({
                    title: '小数点后最多两位!',
                    icon: 'none'
                })
            } else {
                wx.showToast({
                    title: '请输入正确金额',
                    icon: 'none'
                })
            }
            return
        }
        let that = this
        let isOut = that.data.write_kind_list[0].choose
        let categoryId
        let categoryName
        if (isOut) {
            that.data.kind_list_out.forEach((item) => {
                if (item.choose) {
                    categoryId = item.categoryId
                    categoryName = item.categoryName
                }
            })
        } else {
            that.data.kind_list_in.forEach((item) => {
                if (item.choose) {
                    categoryId = item.categoryId
                    categoryName = item.categoryName
                }
            })
        }
        wx.request({
            url: app.globalData.url + '/up_bill',
            method: 'POST',
            header: {
                'content-type': 'application/json'
            },
            data: {
                id: this.data.billId,
                userId: wx.getStorageSync('userInfo').id,
                isOut: isOut,
                categoryId: categoryId,
                categoryName: categoryName,
                money: money,
                remark: remark,
                createTime: util.formatTime(new Date(this.data.currentDate)),
                // groupId: wx.getStorageSync('userInfo').groupVO.id
                groupId: this.data.chooseGroup.groupId
            },
            success: (res) => {
                if (res.data.flag) {
                    wx.showToast({
                        title: '保存成功^_^',
                        icon: 'success'
                    })
                    // for (let index = 0; index < this.data.originalGroupList.length; index++) {
                    //     if (this.data.originalGroupList[index].id == this.data.chooseGroup.groupId) {
                    //         let userInfo = wx.getStorageSync('userInfo');
                    //         userInfo.groupVO = this.data.originalGroupList[index]
                    //         wx.setStorageSync('userInfo', userInfo);
                    //         break
                    //     }
                    // }
                    if (1 == isGoon) {
                        this.setData({
                            billId: null,
                            currentDate: new Date().getTime(),
                            inputvalue: '',
                            set_money: '',
                            add_date_show: '今天',
                            isFocus: true
                        });
                    } else {
                        wx.switchTab({
                            url: '/pages/index/index'
                        })
                    }
                } else {
                    wx.showToast({
                        title: '保存失败，请稍后尝试',
                        icon: 'none'
                    })
                }
            },
            fail: (err) => {
                console.log('失败', err);
            }
        })

    },
    show(param, options) {
        let categoryId = 0
        if (options.categoryId) {
            categoryId = options.categoryId
        } else {
            categoryId = param.outCategory[0].categoryId
        }
        this.getRemarkByCategory(categoryId)
        let that = this
        let outList = param.outCategory
        let inList = param.inCategory
        // 修改
        if (null != options.billId) {
            // 支出/收入
            let write_kind_list = this.data.write_kind_list
            write_kind_list.forEach((item) => {
                item.choose = false
            })
            if (options.isOut === "true") {
                write_kind_list[0].choose = true
            } else {
                write_kind_list[1].choose = true
            }
            this.setData({
                write_kind_list
            })

            // 选择类别
            if (options.isOut === "true") {
                outList.forEach((item) => {
                    item.choose = false
                    if (item.categoryId == options.categoryId) {
                        item.choose = true
                    }
                })
            } else {
                inList.forEach((item) => {
                    item.choose = false
                    if (item.categoryId == options.categoryId) {
                        item.choose = true
                    }
                })
            }
            that.setData({
                billId: options.billId,
                currentDate: new Date(options.createTime).getTime(),
                inputvalue: options.remark,
                set_money: options.money
            })

            let chooseYear = new Date(this.data.currentDate).getFullYear()
            let chooseMonth = new Date(this.data.currentDate).getMonth() + 1
            let chooseDay = new Date(this.data.currentDate).getDate()
            let nowYear = new Date().getFullYear()
            let nowMonth = new Date().getMonth() + 1
            let nowDay = new Date().getDate()

            if (chooseYear == nowYear && chooseMonth == nowMonth && chooseDay == nowDay) {
                this.setData({
                    add_date_show: '今天',
                });
            } else {
                this.setData({
                    add_date_show: chooseMonth + '-' + chooseDay
                });
            }
        } else {
            this.setData({
                currentDate: new Date().getTime()
            })
        }
        this.setData({
            kind_list_out: outList,
            kind_list_in: inList,
        })
    },
    getRemarkByCategory(categoryId) {
        // 获取备注提示
        wx.request({
            url: app.globalData.url + '/getRemark',
            method: 'GET',
            data: {
                userId: wx.getStorageSync('userInfo').id,
                categoryId: categoryId
            },
            success: (res) => {
                if (res.data.flag) {
                    // console.log(res.data.data)
                    this.setData({
                        remarkList: res.data.data,
                    })
                }
            },
            fail: (err) => {
                console.log('查询失败，请稍后尝试!!!', err);
            }
        })
    },
    choseRemark(e) {
        this.setData({
            inputvalue: e.currentTarget.dataset.value,
            isFocusForRemark: true
        })
    },
    onChangeMoney(e) {
        if (this.data.timeoutID) {
            clearTimeout(this.data.timeoutID)
        }
        if (this.data.delayTime == 0) {
            return
        }
        if (e.detail.value.length > 0) {
            let that = this
            let timeoutID = setTimeout(function () {
                that.setData({
                    isFocusForRemark: true
                })
            }, that.data.delayTime);
            this.setData({
                timeoutID: timeoutID
            })
        }
    },
    /**
     * 生命周期函数--监听页面
     */
    onLoad: function (options) {
        wx.hideShareMenu({
            menus: ['shareAppMessage', 'shareTimeline']
        })
        app.globalData.loginToAdd = 0
        let that = this
        request({
            url: "/getCategoryByGroupId",
            method: "GET",
            data: {
                groupId: wx.getStorageSync('userInfo').groupVO.id,
                userId: wx.getStorageSync('userInfo').id
            }
        }).then((responseData) => {
            that.show(responseData, options)
        })
    },

    /**
     * 生命周期函数--监听页面显示请求数据
     */
    onShow: function () {
        if (wx.getStorageSync('configColor') !== this.data.configColor) {
            this.setData({ configColor: wx.getStorageSync('configColor') });
        }
        let delayTime = 0;
        switch (wx.getStorageSync('userInfo').focusTime) {
            case "0":
                break;
            case "1":
                delayTime = 500
                break;
            case "2":
                delayTime = 800
                break;
            case "3":
                delayTime = 1000
                break;
        }
        this.setData({
            delayTime: delayTime
        })
        wx.request({
            url: app.globalData.url + '/getGroupByUser',
            method: 'GET',
            data: {
                userId: wx.getStorageSync('userInfo').id,
            },
            success: (res) => {
                let groupList = []
                let list = res.data.data
                this.setData({
                    originalGroupList: list
                })
                let indexTemp = 1
                list.forEach((item) => {
                    if (item.active != 2) {
                        return
                    }
                    let groupTemp = { text: '', value: 0, groupId: item.id }
                    groupTemp.text = item.name
                    groupTemp.value = indexTemp++
                    groupList.push(groupTemp)
                    if (item.choose == 1) {
                        this.setData({
                            chooseGroup: groupTemp,
                            showGroupIndex: groupTemp.value
                        })
                    }
                })
                this.setData({
                    groups: groupList
                })
            },
            fail: (err) => {
                console.log('失败', err);
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})



